package com.pl.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.MultipartConfigElement;

/**
 * @author shent
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Value("${file.fileImgUpload}")
    String imgUpload;
    @Value("${file.staticPath}")
    String staticPath;

    /**
     * 图片上传配置
     *
     * @return
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // 配置上传文件的目录
        factory.setLocation(imgUpload);
        //文件最大KB,MB
        factory.setMaxFileSize(DataSize.parse("1024MB"));
        //设置总上传数据总大小
        factory.setMaxRequestSize(DataSize.parse("1024MB"));
        return factory.createMultipartConfig();
    }

    /**
     * imgUpload 为图片保存到本地的磁盘路径，staticPath 为ip地址访问虚拟路径
     * 将虚拟路径映射到实际路径,使得前端可以通过访问虚拟路径,获取服务器的图片
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(staticPath + "**").addResourceLocations("file:" + imgUpload);
    }

}
